package com.qf.bookshop2.realm;


import com.qf.bookshop2.model.User;
import com.qf.bookshop2.service.PermisstionService;
import com.qf.bookshop2.service.RoleService;
import com.qf.bookshop2.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;



import java.util.List;

public class MyRealm extends AuthorizingRealm {

    RoleService roleService;
    PermisstionService permisstionService;
    UserService userService;

    public RoleService getRoleService() {
        return roleService;
    }

    public void setRoleService(RoleService roleService) {
        this.roleService = roleService;
    }

    public PermisstionService getPermisstionService() {
        return permisstionService;
    }

    public void setPermisstionService(PermisstionService permisstionService) {
        this.permisstionService = permisstionService;
    }

    public UserService getUserService() {
        return userService;
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取用户名
        String username = (String) principalCollection.getPrimaryPrincipal();
        System.out.println("================="+username);
        //roles 根据传过来的用户名得到用户所具有的的角色
        //perms 根据传过来的用户名得到用户所具有的的权限


        List<String> listRole = roleService.getRolesByUsername(username);

        List<String> permisstionStringList = permisstionService.getPermisstionStringList(username);
        System.out.println(listRole.toString());
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        info.addRoles(listRole);
        info.addStringPermissions(permisstionStringList);
        //权限

        return info;
    }
    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获取用户名
        String username = (String) authenticationToken.getPrincipal();
        System.out.println(username+"================");


        System.out.println(userService+"=======================");
        User user = userService.getUserByUsername(username);
        //如果user对象为空，直接返回空给sm
        if(user==null){
            return null;
        }
        AuthenticationInfo info=

                new SimpleAuthenticationInfo(user.getUsername(),user.getPassword(),
//                        ByteSource.Util.bytes(user.getSalt()),
                        this.getName());

        return info;
    }
}
